<?php

/**
 * Portal PSG - Polska Strefa Graffiti
 * 
 * Strona logowania do Portalu
 */
require_once '../_boot.php'; // import biblioteki rozruchowej

RunApplication(APP_DOMAIN, APP_URLPATH, APP_PORT);

import('Psg.Auth');
import('Psg.Core');

if (isset($_GET['logout'])) {
    session_destroy();
    setcookie('PSG_PERMLOGINTOKEN', '', time()-3600);
    setcookie('PSG_PERMLOGINUSER', '', time()-3600);
    Url::redirect();
} else if (Psg\Auth::isLoggedIn()) {
    Url::redirect();
} else if (isset($_GET['login'], $_GET['request'])) {
    if (\Psg\Auth::loginTokenExists($_GET['login'], $_GET['request'])) {
        if (isset($_GET['permament'])) {
            setcookie('PSG_PERMLOGINTOKEN', \Psg\Auth::setPermamentToken($_GET['login']), time() + 3600 * 24 * 15, '/', APP_DOMAIN);
            setcookie('PSG_PERMLOGINUSER', $_GET['login'], time() + 3600 * 24 * 15, '/', APP_DOMAIN);
        }
        $_SESSION['email'] = $_GET['login'];
        $_SESSION['nick'] = Psg\Core::getUserInfo($_GET['login'])['nick'];
    }
    Url::redirect();
} else if (isset($_COOKIE['PSG_PERMLOGINTOKEN'], $_COOKIE['PSG_PERMLOGINUSER'])) {
    if (\Psg\Auth::permamentTokenExist($_COOKIE['PSG_PERMLOGINUSER'], $_COOKIE['PSG_PERMLOGINTOKEN'])) {
        $_SESSION['email'] = $_COOKIE['PSG_PERMLOGINUSER'];
        $_SESSION['nick'] = Psg\Core::getUserInfo($_COOKIE['PSG_PERMLOGINUSER'])['nick'];
    } else {
        setcookie('PSG_PERMLOGINUSER', '', time()-3600);
        setcookie('PSG_PERMLOGINUSER', '', time()-3600);
    }
    Url::redirect();
} else {
    echo View::factory('loginPage');
}

